﻿using NDK.Communacation;
using BZ.Logger;
using NDK.Module.Model;
using NDK.Module.Model.Quebec;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;

namespace NDK.Module.StationLogic
{
    class StationServer
    {
        public ECommunacation SocketAlgo_CarrierA = null;
        public ECommunacation SocketAlgo_CarrierB = null;
        //public ECommunacation SocketOtherSide = null;
        //public ECommunacation SocketRightSide = null;
        public static List<ReturnProtocol> msgList_CarrierA = new List<ReturnProtocol>();
        public static List<ReturnProtocol> msgList_CarrierB = new List<ReturnProtocol>();

        public ECommunacation SocketLoadingDevice = null;

        public static StationServer Instance = new StationServer();
      
        public static bool OtherSideInit()
        {
            bool ret = true;
            //if (Common.Line.Equals(Common.LineName.左.ToString()))
            //    ret &= ClientInit();
            //else
            //    ret &= ServerInit();
            return ret;
        }

 
        #region 左右线通讯  右侧是服务器，左侧是客户端

        #region 服务器
        public static bool ServerInit()
        {
            string hostServerCom = EComManageer.CreateECom(CommunicationModel.TcpServer);
            Common. SocketOtherSide = EComManageer.GetECommunacation(hostServerCom);
            Common. SocketOtherSide.LocalPort = 2100;
            Common.SocketOtherSide.ReceiveString += ServerReceiveString;
            EComManageer.Connect(hostServerCom);
            Thread.Sleep(5000);
            if (Common.SocketOtherSide?.IsConnected==true)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public static bool SendStr_Server(string str)
        {
            bool ret = Common.SocketOtherSide.SendStr(str);
            if (!ret)
            {
                Common.AppendUiLog.Log($"Server发送打开放NG信号失败: {str}", LogType.Error);
            }
            else
            {
                Common.AppendUiLog.Log($"Server发送打开放NG信号: {str}", LogType.Alert);
            }
            return ret;
        }

        public static void ServerReceiveString(string str)
        {
            Common.AppendUiLog.Log($"服务器接收到左侧:{str}", LogType.Alert);


            string[] message = str.Trim().Split('#');
            str = string.Empty;
            for (int i = 0; i < message.Length; i++)
            {
                string Str_Split = string.Empty;
                var splitList = message[i].Trim().Split('@').ToList();//strrecv
                str = string.Empty;
                Str_Split = splitList[0].Trim();

                if (Str_Split == "PutNG")
                {
                    Common.b_左侧请求放NG = true;
                }
                if (Str_Split == "OpenOK")
                {
                    Common.b_左侧已经打开NG信号 = true;
                }

                if (Str_Split == "PutORT")
                {
                    Common.b_左侧请求放ORT = true;
                }
                if (Str_Split == "OpenORTOK")
                {
                    Common.b_左侧已经打开ORT信号 = true;
                }
                if (Str_Split == "CatchFinish")
                {
                    Common.b_双动子收到左侧取料完成信号 = true;
                }
                if (Str_Split == "CloseVaccumFinish")
                {
                    Common.b_双动子收到左侧关闭真空完成 = true;
                }
                if (Str_Split == "Result")
                {
                    Common.Result_左侧 = splitList[1].Trim();
                }

                if (Str_Split == "AllowPut")
                {
                    Common.b_左侧允许PLC放料 = true;
                }

                if (Str_Split == "AllowLeave")
                {
                    Common.b_左侧允许PLC离开 = true;
                }

                if (Str_Split == "CopyLeave")
                {
                    Common.b_左侧收到PLC已离开 = true;
                }

            }
        }
        #endregion

        #region 客户端
        public static bool ClientInit()
        {
            string hostServerCom = EComManageer.CreateECom(CommunicationModel.TcpClient);
            Common.SocketRightSide = EComManageer.GetECommunacation(hostServerCom);
            Common.SocketRightSide.RemoteIP = Common.左侧工控机IP;      
            Common.SocketRightSide.RemotePort = 2100;
            Common.SocketRightSide.ReceiveString += ClientReceiveString;
            EComManageer.Connect(hostServerCom);
            Thread.Sleep(5000);
            if (Common.SocketRightSide?.IsConnected==true)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public static bool SendStr_Client(string str)
        {
            bool ret = Common.SocketRightSide.SendStr(str);
            if (!ret)
            {
                Common.AppendUiLog.Log($"Client发送请求放NG失败: {str}", LogType.Error);
            }
            else
            {
                Common.AppendUiLog.Log($"Client发送请求放NG: {str}", LogType.Alert);
            }
            return ret;
        }

        public static void ClientReceiveString(string str)
        {
            string[] message = str.Trim().Split('#');
            str = string.Empty;

            for (int i = 0; i < message.Length; i++)
            {

                string Str_Split = string.Empty;
                var splitList = message[i].Trim().Split('@').ToList();//strrecv
                str = string.Empty;
                Str_Split = splitList[0].Trim();

                if (Str_Split == "Standby")
                {
                    Common.b_左侧收到双动子允许接料信号 = true;
                }

                if (Str_Split == "CloseVaccum")
                {
                    Common.b_双动子允许关闭真空信号 = true;
                }

                if (Str_Split == "RequirePut")
                {
                    Common.b_上料PLC请求放左侧 = true;
                }

                if (Str_Split == "PutInPos")
                {
                    Common.b_上料PLC左侧运动到位 = true;
                }

                if (Str_Split == "PutFinish")
                {
                    Common.b_上料PLC左侧已离开 = true;
                }

                if (Str_Split == "Barcode")
                {
                    Common.str_左侧二维码 = splitList[1].Trim(); ;
                }
            }

            Common.AppendUiLog.Log($"客户端接收到:{str}", LogType.Alert);
        }
        #endregion

        #endregion

        #region 和上料机通讯
        public static bool LoadingDeviceClientInit()  //右侧"192.168.10.211", 2000 左侧 "192.168.10.210", 2000
        {
            if (Common.是否联机上料PLC)
            {
                string hostServerCom = EComManageer.CreateECom(CommunicationModel.TcpClient);
                Instance.SocketLoadingDevice = EComManageer.GetECommunacation(hostServerCom);

                Instance.SocketLoadingDevice.RemoteIP = "192.168.10.210";
                Instance.SocketLoadingDevice.RemotePort = 2000;

                Instance.SocketLoadingDevice.ReceiveString += LoadingDeviceReceiveString;
                if (EComManageer.Connect(hostServerCom))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return true;
            }
        }

        public static void LoadingDeviceReceiveString(string str)
        {
            WriteLogToTxt($"接收到上料机:{str}", "Log_接收上料机");
            string Str_Split = string.Empty;
            Str_Split = str.Split(':')[1].Trim().ToString();
            Common.BarcodeQueue.Enqueue(Str_Split);
            str = string.Empty;
        }

        public static bool Loading_SendStr(string cmd)
        {
            bool ret = Instance.SocketLoadingDevice.SendStr(cmd);
            if (!ret)
            {
                Common.AppendUiLog.Log($"发送上料机失败: {cmd}", LogType.Alert);
            }
            else
            {
                Common.AppendUiLog.Log($"发送上料机成功: {cmd}", LogType.Alert);
            }
            return ret;
        }
        #endregion

        private static void WriteLogToTxt(string strLog, string FileName)
        {

            String System_Now_Time = null;
            String File_Create_Time = null;

            System_Now_Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff"); //"HH:mm:ss
            File_Create_Time = DateTime.Now.ToString("yyyyMMdd");
            string logDocument = File_Create_Time + ".txt";

            string str = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
            string logFilePath = str.Substring(0, str.LastIndexOf("\\")) + "\\" + FileName;//VisionSendMessage";
            if (!Directory.Exists(logFilePath))
            {
                Directory.CreateDirectory(logFilePath);
            }
            logFilePath = logFilePath + "//" + logDocument;
            FileStream fs = new FileStream(logFilePath, FileMode.Append);
            StreamWriter sw = new StreamWriter(fs, Encoding.Default);
            sw.WriteLine(System_Now_Time + ":   " + strLog);
            sw.Flush();
            sw.Close();
            fs.Close();

        }
    }
}
